﻿using System;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace XFGameFramework
{ 
    /// <summary>
    /// 项目全局设置(配置文件保存在Assets的同级目录ProjectSettings下面)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ProjectSettingsScriptableObject<T> : ScriptableObject where T : ScriptableObject
    {
        private static T instance;
        public static T Instance
        {
            get
            {
                if (!instance)
                {
                    LoadOrCreate();
                }
                return instance;
            }
        }
        public static void LoadOrCreate()
        {
            string filePath = GetFilePath();
            
            var arr = InternalEditorUtility.LoadSerializedFileAndForget(filePath);
          
            if (arr.Length > 0) 
            {
                instance = arr[0] as T;
            }

            if (instance == null) 
            {
                instance = CreateInstance<T>();
                Save();
            }

        }

        public static void Save(bool saveAsText = true)
        { 

            string filePath = GetFilePath();
            if (!string.IsNullOrEmpty(filePath))
            {
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                UnityEngine.Object[] obj = new T[1] { instance };
                InternalEditorUtility.SaveToSerializedFileAndForget(obj, filePath, saveAsText);
            }
        }
        protected static string GetFilePath()
        {  
            return string.Format("ProjectSettings/{0}.asset", typeof(T).FullName);
        }


        public void OpenProjectSettings(string path)
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var item in assemblies)
            {
                Type t = item.GetType("UnityEditor.SettingsWindow");
                if (t == null) continue;
                MethodInfo ShowProjectSettingsMethod = t.GetMethod("Show", BindingFlags.Static | BindingFlags.NonPublic);
                ShowProjectSettingsMethod.Invoke(null, new object[] { SettingsScope.Project, path });
            }
        }

    } 
}

